<template>
  <el-form ref="aiFormRef" :model="aiForm" :rules="aiRules" label-width="100px">
    <el-form-item label="API Token" prop="token">
      <el-input v-model="aiForm.token" placeholder="请输入个人API Token" type="password" show-password />
      <div class="tips">
        <el-alert
          title="自定义API Token会替代系统默认配置，所有AI功能将使用您提供的Token"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button type="danger" @click="handleClear">清除</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getCustomAIToken, setCustomAIToken, clearCustomAIToken } from '@/utils/aiToken';

// 表单引用
const aiFormRef = ref(null);

// 表单数据
const aiForm = reactive({
  token: ''
});

// 表单校验规则
const aiRules = {
  token: [
    { required: false, message: '请输入API Token', trigger: 'blur' }
  ]
};

// 页面加载时从本地存储获取token
onMounted(() => {
  const savedToken = getCustomAIToken();
  if (savedToken) {
    aiForm.token = savedToken;
  }
});

// 保存设置
const handleSave = () => {
  aiFormRef.value.validate(valid => {
    if (valid) {
      if (aiForm.token.trim()) {
        setCustomAIToken(aiForm.token);
        ElMessage.success('API Token保存成功');
      } else {
        handleClear();
      }
    }
  });
};

// 清除设置
const handleClear = () => {
  clearCustomAIToken();
  aiForm.token = '';
  ElMessage.success('已清除自定义API Token');
};
</script>

<style scoped>
.tips {
  margin-top: 10px;
}
</style> 